//
//  DSZClassifyViewController.m
//  7.13苏宁框架
//
//  Created by app20 on 15/7/15.
//  Copyright (c) 2015年 lovena. All rights reserved.
//

#import "DSZClassifyViewController.h"
#import "DSZClassifyShopsViewController.h"
#import "DSZLYViewController.h"
#import "DSZClassifyShopsModel.h"
#import "DSZClassifyShopsCell.h"
#import "Common.h"
#import "DSZMainViewController.h"
@interface DSZClassifyViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIScrollViewDelegate,DSZClassifyShopsCellDelegate>

@property(nonatomic,weak) UITableView *classifyTV;
@property(nonatomic,weak) UITableView *classifyShopsTV;
@property(nonatomic,weak) UITableViewCell *lastCell;
@property(nonatomic,weak) UITextField *navTextFiled;
@property(nonatomic,weak) UIScrollView *TFHotWordsHistoryView;
@property(nonatomic,assign) NSInteger index;
@property(nonatomic,assign) CGFloat btnY;

@property(nonatomic,strong) NSArray *classifyArray;
@property (weak, nonatomic) UIView *classifyHeaderView;
@property (weak, nonatomic)  UIScrollView *tableHeaderScrollView;
@property (weak, nonatomic) UIButton *lastClikPageBtn;
@property(nonatomic,assign) NSInteger currentPage;
@property(nonatomic,assign) NSInteger numberOfPages;

//定时器
@property (nonatomic, strong) NSTimer *timer;



@end


@implementation DSZClassifyViewController

- (void)requestData{

    NSArray *result = [WXNetworkService classifyData];
    
    _classifyArray=[NSArray array];
    _classifyArray=[DSZClassifyShopsModel modelArrayWithDictArray:result];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 加载数据
    [self requestData];
    
    // 加载搜索框
    [self loadTextFiled];
    
    // 加载分类左侧表
    [self loadClasifyTV];
    
    // 纪录选中的行
    _lastCell.selected = YES;
    
    // 初始化左侧分类表选中行号
    _index = 0;
    
    // 初始化当前页
    _currentPage = 0;
    
}

-(void)viewWillAppear:(BOOL)animated
{
    DSZMainViewController *main=(DSZMainViewController *)self.tabBarController;
    [main hiddenMainTabbar:NO];
    self.navigationController.navigationBarHidden = NO
    ;
}

- (void)loadTextFiled{

    // 自定义导航栏视图
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 44)];
    
    // 添加取消按钮
    UIButton *navCancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(250, 7, 40, 30)];
    navCancelBtn.font = [UIFont systemFontOfSize:14];
    [navCancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [navCancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [navCancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [navCancelBtn addTarget:self action:@selector(clickCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:navCancelBtn];
    
    // 添加搜索框
    UITextField *navTextFielfd = [[UITextField alloc] initWithFrame:CGRectMake(0, 7, 290, 30)];
    navTextFielfd.borderStyle = UITextBorderStyleRoundedRect;
    navTextFielfd.placeholder = @"三星A8 震撼首发";
    navTextFielfd.font = [UIFont systemFontOfSize:15];
    navTextFielfd.clearButtonMode = UITextFieldViewModeWhileEditing;
    navTextFielfd.returnKeyType = UIReturnKeySearch;
    navTextFielfd.delegate = self;
    _navTextFiled = navTextFielfd;
    [navView addSubview:navTextFielfd];
    
    // 给搜索框添加左辅助视图
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(5, 2.5, 40, 25)];

    [leftBtn setTitle:@"商品" forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [leftBtn setTitle:@"店铺" forState:UIControlStateSelected];
    [leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    leftBtn.font = [UIFont systemFontOfSize:14];
    
    [leftBtn addTarget:self action:@selector(clickLeftBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *rightImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btnDownArrow_icon.png"]];
    rightImageView.frame = CGRectMake(leftBtn.frame.size.width + 5, leftBtn.frame.size.height / 2 , 10, 5);
    [leftView addSubview:leftBtn];
    [leftView addSubview:rightImageView];
    
    navTextFielfd.leftView = leftView;
    navTextFielfd.leftViewMode = UITextFieldViewModeAlways;
    
    
    // 给搜索框添加右辅助视图
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 15)];
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, rightView.frame.size.width - 8, rightView.frame.size.height )];

    [rightBtn setBackgroundImage:[UIImage imageNamed:@"homeSearchTool_voiceIcon.png"] forState:UIControlStateNormal];
    
    [rightBtn addTarget:self action:@selector(clickRightBtn) forControlEvents:UIControlEventTouchUpInside];
    
    [rightView addSubview:rightBtn];
    
    navTextFielfd.rightView = rightView;
    navTextFielfd.rightViewMode = UITextFieldViewModeAlways;
    
    
    UIBarButtonItem *customLeftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:navView];
    
    self.navigationItem.leftBarButtonItem = customLeftBarButtonItem;
}

// 加载分类表视图
- (void)loadClasifyTV{

    UITableView *classifyTV = [[UITableView alloc] initWithFrame:CGRectMake(-0, 0, 90, KDeviceHeight) style:UITableViewStylePlain];
    
    classifyTV.dataSource = self;
    classifyTV.delegate = self;
    
    classifyTV.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    
    classifyTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _classifyTV = classifyTV;
    
    [self.view addSubview:classifyTV];
    
}

- (void)loadClassifyShopsTV{

    UITableView *classifyShopsTV = [[UITableView alloc] initWithFrame:CGRectMake(_classifyTV.size.width, 64, self.view.size.width - _classifyTV.size.width, self.view.size.height- 24 - 49) style:UITableViewStyleGrouped];
    classifyShopsTV.dataSource = self;
    classifyShopsTV.delegate = self;
    classifyShopsTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    classifyShopsTV.backgroundColor = [UIColor whiteColor];
    _classifyShopsTV = classifyShopsTV;
    [self.view addSubview:classifyShopsTV];
    
    // 添加表头视图
    UIView *classifyHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 230, 85)];
    UIScrollView *tableHeaderScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(5, 5, classifyHeaderView.width - 10, 50)];
    [classifyHeaderView addSubview:tableHeaderScrollView];
    
    // 想表头添加第一段段头
    UIView *sectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 230, 15)];
    
    UIView *blackView = [[UIView alloc] initWithFrame:CGRectMake(5, classifyHeaderView.height - 15, 5, sectionHeaderView.height)];
    blackView.backgroundColor = [UIColor blackColor];
    
    UILabel *sectionHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake(blackView.width + blackView.left + 10, classifyHeaderView.height - 15, 100, sectionHeaderView.height)];
    sectionHeaderLabel.text = [[[_classifyArray[_index] subject] objectForKey:@"body"][0] objectForKey:@"title"];
    sectionHeaderLabel.font = [UIFont systemFontOfSize:13];
    [classifyHeaderView addSubview:blackView];
    [classifyHeaderView addSubview:sectionHeaderLabel];
    
    _classifyHeaderView = classifyHeaderView;
    _tableHeaderScrollView = tableHeaderScrollView;
    
    // 1.添加图片到scrollView中
    for (int i = 0; i < [[[_classifyArray[_index] subject] objectForKey:@"header"] count]; i++) {
        
        // 添加轮转图片
        UIImageView *imageView = [[UIImageView alloc] init];
        
        // 设置frame
        imageView.frame = CGRectMake(tableHeaderScrollView.width * i, 0, tableHeaderScrollView.width, tableHeaderScrollView.height);
        
        // 设置图片
        NSString *url = [[[_classifyArray[_index] subject] objectForKey:@"header"][i] objectForKey:@"url"];
        [imageView  setImageWithURL:[NSURL URLWithString:url]];
        
        [tableHeaderScrollView addSubview:imageView];
        
        // 添加动作按钮
        UIButton *imageBtn = [[UIButton alloc] initWithFrame:CGRectMake(tableHeaderScrollView.width * i, 0, tableHeaderScrollView.width, tableHeaderScrollView.height)];
        imageBtn.tag = i + 101;
        [tableHeaderScrollView addSubview:imageBtn];
        [imageBtn addTarget:self action:@selector(tableHeaderBtnClickWithBtn:) forControlEvents:UIControlEventTouchUpInside];
//        imageBtn.backgroundColor = [UIColor blackColor];
        
    }
    
    // 2.设置内容尺寸
    CGFloat contentW = [[[_classifyArray[_index] subject] objectForKey:@"header"] count] * tableHeaderScrollView.width;
    
    tableHeaderScrollView.contentSize = CGSizeMake(contentW, 0);
    
    // 3.隐藏水平滚动条
    tableHeaderScrollView.showsHorizontalScrollIndicator = NO;
    
    // 4.分页
    tableHeaderScrollView.pagingEnabled = YES;
    tableHeaderScrollView.delegate = self;
    
    // 5.1设置总页数
    self.numberOfPages = [[[_classifyArray[_index] subject] objectForKey:@"header"] count];
    
    // 5.2自定义分页视图
    if (self.numberOfPages > 1) {
        
        int count = [[[_classifyArray[_index] subject] objectForKey:@"header"] count];
        CGFloat space = 5;
        CGFloat pageBtnW = 8;
        CGFloat pageBtnH = 5;
        CGFloat pageX = classifyHeaderView.width / 2.0 - (space* count + pageBtnW * count - space) / 2.0;
        CGFloat pageY = tableHeaderScrollView.height - 5;
        
        for (int i = 0; i < count; i++) {
            
            CGFloat pageBtnX = pageX + (pageBtnW + space) * i;
            
            // 添加动作按钮
            UIButton *pageBtn = [[UIButton alloc] initWithFrame:CGRectZero];
            pageBtn.layer.cornerRadius = 1;
            pageBtn.clipsToBounds = YES;
            pageBtn.frame = CGRectMake(pageBtnX, pageY, pageBtnW, pageBtnH);
            pageBtn.tag = i + 201;
            pageBtn.backgroundColor = [UIColor whiteColor];
            pageBtn.alpha = 0.5;
            if (i == 0) {
                pageBtn.alpha = 1;
                _lastClikPageBtn = pageBtn;
            }
            [classifyHeaderView addSubview:pageBtn];
            [pageBtn addTarget:self action:@selector(tableHeaderPageBtnClickWithBtn:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        // 6.添加定时器(每隔2秒调用一次self 的nextImage方法)
        [self addTimer];
    }
    
    
    classifyShopsTV.tableHeaderView = classifyHeaderView;
    
    // 设置段头高
    classifyShopsTV.sectionHeaderHeight = 20;
}


/**
 *  添加定时器
 */
- (void)addTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

/**
 *  移除定时器
 */
- (void)removeTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)nextImage
{
        // 1.增加pageControl的页码
//        int page = 0;
//        if (self.tabelHeaderPageControl.currentPage == self.tabelHeaderPageControl.numberOfPages - 1) {
//            page = 0;
//        } else {
//            page = self.tabelHeaderPageControl.currentPage + 1;
//        }
    
    int page = (self.currentPage + 1) % self.numberOfPages;
    self.currentPage =  page;
    
    UIButton *btn = (UIButton *)[self.classifyHeaderView viewWithTag:self.currentPage + 201];
    [self tableHeaderChangePageBtnWithBtn:btn];
    
}

#pragma mark -  scrollViewDelegate
/**
 *  当scrollView正在滚动就会调用
 */
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    // 根据scrollView的滚动位置决定pageControl显示第几页
//    CGFloat scrollW = scrollView.frame.size.width;
//    int page = (scrollView.contentOffset.x + scrollW * 0.5) / scrollW;
//    self.tabelHeaderPageControl.currentPage = page;
//}

/**
 *  开始拖拽的时候调用
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 停止定时器(一旦定时器停止了,就不能再使用)
    [self removeTimer];
}


/**
 *  停止拖拽的时候调用
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
    // 根据scrollView的滚动位置决定pageControl显示第几页
    CGFloat scrollW = scrollView.frame.size.width;
    int page = (scrollView.contentOffset.x + scrollW * 0.5) / scrollW;
    
    if (self.currentPage != page) {
        
        self.currentPage = page;
        
        UIButton *btn = (UIButton *)[self.classifyHeaderView viewWithTag:self.currentPage + 201];
        [self tableHeaderChangePageBtnWithBtn:btn];
    }
    
    // 开启定时器
    [self addTimer];
    
}

// 点击导航栏浏览视图模式按钮
- (void)clickChangeViewBtn:(UIButton *)btn{

    if ([btn isSelected]) {
        
        btn.selected = NO;
    }else{
    
        btn.selected = YES;
    }
}


// 点击导航栏取消按钮
-(void)clickCancelBtn{

    _navTextFiled.frame = CGRectMake(0, _navTextFiled.frame.origin.y, _navTextFiled.frame.size.width + 45, _navTextFiled.frame.size.height);
    _navTextFiled.text = nil;
    [_navTextFiled endEditing:YES];
    
    [_TFHotWordsHistoryView removeFromSuperview];
}

// 点击搜索框左边按钮
-(void)clickLeftBtn:(UIButton *)Btn{

    if ([Btn isSelected]) {
        
        Btn.selected = NO;
    }else{
    
        Btn.selected = YES;
    }
}

// 点击搜索框右边麦克风按钮
-(void)clickRightBtn{

//    UIAlertView *clickMicBtnTip = [[UIAlertView alloc] initWithTitle:nil message:@"暂时无法使用，请到设置中允许使用麦克风" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
//    [clickMicBtnTip show];
    
    
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"DSZLYViewController" bundle:nil];
    DSZLYViewController *vc=[story instantiateViewControllerWithIdentifier:@"lv"];
    //[self.navigationController pushViewController:vc animated:YES];
    [self presentViewController:vc animated:YES completion:nil];
}

// 加载搜索框正在编辑搜索历史视图
- (void)loadTFHotWordsHistoryView{
    
    // 添加背景视图
    UIScrollView *TFHotWordsHistoryView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, self.view.size.width, self.view.size.height - 64 - 216)];
    TFHotWordsHistoryView.backgroundColor = [UIColor colorWithRed:0.90 green:0.90 blue:0.90 alpha:1];
    TFHotWordsHistoryView.delegate = self;
    TFHotWordsHistoryView.directionalLockEnabled = YES;
    TFHotWordsHistoryView.scrollEnabled = YES;
    TFHotWordsHistoryView.showsVerticalScrollIndicator = YES;
    TFHotWordsHistoryView.indicatorStyle = UIScrollViewIndicatorStyleBlack;
    
    // 初始化数据
    CGFloat marginLeft = 10;
    CGFloat marginTop = 15;
    CGFloat tipW = 60;
    CGFloat tipH = 30;
    CGFloat extend = 3;
    CGFloat strLong = 20;
    CGFloat btnX = marginLeft;
    _btnY = marginTop;
    CGFloat btnH = 25;
    CGFloat btnSpace = 10;
    CGFloat rowSpace = 10;
    
    // 添加人们推荐标签
    UILabel *hotWordsTip = [[UILabel alloc] initWithFrame:CGRectMake(btnX, _btnY, tipW, tipH)];
    hotWordsTip.backgroundColor = [UIColor clearColor];
    hotWordsTip.text = @"热门推荐";
    hotWordsTip.font = [UIFont systemFontOfSize:15];
    hotWordsTip.textColor = [UIColor grayColor];
    [TFHotWordsHistoryView addSubview:hotWordsTip];
    
    _btnY = _btnY + tipH + rowSpace;
    
    for (int i = 0; i < [[_classifyArray[0] hotwords] count]; i++) {
        
        NSString *title = [[_classifyArray[0] hotwords][i] objectForKey:@"hotword"];
        NSInteger numOfStr = title.length;
        CGFloat btnW = extend * 2 + strLong * numOfStr;
        
        if (btnX + btnW > TFHotWordsHistoryView.width - marginLeft - 10) {
            
            btnX = marginLeft;
            _btnY = _btnY + btnH + rowSpace;
        }
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(btnX, _btnY, btnW, btnH)];
        [btn setTitle:title forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.font = [UIFont systemFontOfSize:14];
        btn.backgroundColor = [UIColor whiteColor];
        
        [btn addTarget:self action:@selector(didClickHotWordsBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        
        [TFHotWordsHistoryView addSubview:btn];
        
        btnX = btnX + btnW + btnSpace;
    }
    
    btnX = marginLeft;
    _btnY = _btnY + btnH + marginTop;
    
    _TFHotWordsHistoryView = TFHotWordsHistoryView;
    
    [self.view addSubview:TFHotWordsHistoryView];

}

- (void)didClickHotWordsBtn:(UIButton *)btn{
    
    [_TFHotWordsHistoryView removeFromSuperview];
    [self loadTFHotWordsHistoryView];
    
    // 解归档，获取历史纪录数组
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"historyBtns.data"];

    NSMutableArray *historyBtns = [NSMutableArray array];
    
    //  如果解归档为空，不做操作
    if ([NSKeyedUnarchiver unarchiveObjectWithFile:filePath]) {
        
        historyBtns = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    }
    
    // 如果btn为空 不做操作，不为空，复制按钮并放入历史数组
    if (btn) {
        
        UIButton *historyBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [historyBtn setTitle:btn.titleLabel.text forState:UIControlStateNormal];
        [historyBtn setTitleColor:btn.titleLabel.textColor forState:UIControlStateNormal];
        historyBtn.frame = btn.frame;
        
        historyBtn.backgroundColor = btn.backgroundColor;
        
        [historyBtns insertObject:historyBtn atIndex:0];
        
        if (historyBtns.count > 5) {
            
            [historyBtns removeLastObject];
        }
        
        [NSKeyedArchiver archiveRootObject:historyBtns toFile:filePath];
    
    }

    CGFloat marginLeft = 10;
    CGFloat btnX = marginLeft;
    CGFloat btnSpace = 10;
    CGFloat rowSpace = 10;
    CGFloat tipW = 60;
    CGFloat tipH = 30;
    
    if (btn || [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]) {
        
        // 添加历史记录标签
        UILabel *historyTip = [[UILabel alloc] initWithFrame:CGRectMake(btnX, _btnY, tipW, tipH)];
        historyTip.backgroundColor = [UIColor clearColor];
        historyTip.text = @"历史记录";
        historyTip.font = [UIFont systemFontOfSize:15];
        historyTip.textColor = [UIColor grayColor];
        [_TFHotWordsHistoryView addSubview:historyTip];
        
        _btnY = _btnY + tipH + rowSpace;
    }
    
    for (UIButton *subBtn in historyBtns) {
        
        if (btnX + subBtn.width > _TFHotWordsHistoryView.width - marginLeft * 2) {
            
            btnX = marginLeft;
            
            _btnY += subBtn.height + rowSpace;
        }
        
        subBtn.frame = CGRectMake(btnX, _btnY, subBtn.width, subBtn.height);
        subBtn.font = [UIFont systemFontOfSize:14];
        [_TFHotWordsHistoryView addSubview:subBtn];
        
        [subBtn addTarget:self action:@selector(didClickHotWordsBtn:) forControlEvents:UIControlEventTouchUpInside];
        btnX = btnX + subBtn.width + btnSpace;
    }
    
    // 添加清除历史按钮
    _btnY += btn.height + 40;
    marginLeft += 10;
    CGFloat cleanHistoryBtnH = 30;
    
    if (historyBtns.count) {
        
        UIButton *cleanHistoryBtn = [[UIButton alloc] initWithFrame:CGRectMake(marginLeft, _btnY, _TFHotWordsHistoryView.width - marginLeft *2, cleanHistoryBtnH)];
        [cleanHistoryBtn setBackgroundImage:[UIImage imageNamed:@"btnBack.png"] forState:UIControlStateNormal];
        [cleanHistoryBtn setTitle:@"清除历史" forState:UIControlStateNormal];
        [cleanHistoryBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [cleanHistoryBtn addTarget:self action:@selector(didClickClearHistoryBtn) forControlEvents:UIControlEventTouchUpInside];
        [_TFHotWordsHistoryView addSubview:cleanHistoryBtn];
        _btnY += cleanHistoryBtnH * 4;
    }
    
    _TFHotWordsHistoryView.contentSize = CGSizeMake(self.view.width, _btnY);
}

-(void)didClickClearHistoryBtn{

    [_TFHotWordsHistoryView removeFromSuperview];
    [self loadTFHotWordsHistoryView];
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"historyBtns.data"];
    
    [NSKeyedArchiver archiveRootObject:nil toFile:filePath];
    
    UILabel *tip = [[UILabel alloc] initWithFrame:CGRectMake(10, _btnY + 35, _TFHotWordsHistoryView.width - 10 * 2, 20)];
    tip.text = @"历史纪录清除成功";
    tip.font = [UIFont systemFontOfSize:12];
    tip.textAlignment = NSTextAlignmentCenter;
    [_TFHotWordsHistoryView addSubview:tip];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    _navTextFiled.frame = CGRectMake(0, _navTextFiled.frame.origin.y, _navTextFiled.frame.size.width - 45, _navTextFiled.frame.size.height);
    
    [self didClickHotWordsBtn:nil];

    return YES;
}

#pragma mark - TableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (tableView == _classifyTV) {
        
        return 1;
        
    }else{
        
        return [[[_classifyArray[_index] subject] objectForKey:@"body"] count];
    }

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (tableView == _classifyTV) {
        
        return _classifyArray.count;
        
    }else{
    
        return [[[[_classifyArray[_index] subject] objectForKey:@"body"][section] objectForKey:@"section"] count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == _classifyTV) {
        // 定义静态标识符
        static NSString *cellIdentifier = @"classCell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        if (cell == nil) {
            
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            
        }
        
        cell.textLabel.text = [_classifyArray[indexPath.row] title];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textColor = [UIColor blackColor];
        
        cell.backgroundColor = [UIColor clearColor];
        
        // 选中单元格背景图
        UIView *selectedBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 90, 44)];
        selectedBG.backgroundColor = [UIColor whiteColor];
        UIView *selectedBGLeft = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 3, 44)];
        selectedBGLeft.backgroundColor = [UIColor orangeColor];
        
        [selectedBG addSubview:selectedBGLeft];
        
        cell.selectedBackgroundView = selectedBG;
        
        // 默认选中第一行
        if (indexPath.row == 0 && _index == 0) {
            
            [self.classifyTV selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
            
            [self loadClassifyShopsTV];
        }
        
        _index = indexPath.row;
        
        return cell;
        
    }else{
    
        // 定义静态标识符
        static NSString *shopsCellIdentifier = @"classShopsCell";
        
        DSZClassifyShopsCell *cell = [tableView dequeueReusableCellWithIdentifier:shopsCellIdentifier];
        
        if (cell == nil) {
            
            cell = [[DSZClassifyShopsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:shopsCellIdentifier];
            
            cell.delegate = self;
        }
        cell.backgroundColor =  [UIColor  clearColor];
        
        cell.btnArray = [[[_classifyArray[_index] subject] objectForKey:@"body"][indexPath.section] objectForKey:@"section"][indexPath.row];
        
        
        
        return cell;
    }

}

#pragma mark - TableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [self removeTimer];
    
    [_classifyShopsTV removeFromSuperview];
    
    if (tableView == _classifyTV) {
        
        UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
        
        _lastCell.textLabel.textColor = [UIColor blackColor];
        
        selectedCell.textLabel.textColor = [UIColor orangeColor];
        
        _lastCell = selectedCell;
        
        _index = indexPath.row;
        
        [self loadClassifyShopsTV];
        
//        [_classifyShopsTV reloadData];
        
    }else{}
}// 选中某一行

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _classifyTV) {
        
        return 44;
        
    }else{
    
        return 100;
    }
    
}// 设置行高

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    if (tableView == _classifyTV) {
        
        return nil;
        
    }else{
    
        UIView *sectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 230, 15)];
        
        UIView *blackView = [[UIView alloc] initWithFrame:CGRectMake(5, 0, 5, sectionHeaderView.height)];
        blackView.backgroundColor = [UIColor blackColor];
        
        UILabel *sectionHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake(blackView.width + blackView.left + 10, 0, 100, sectionHeaderView.height)];
        sectionHeaderLabel.text = [[[_classifyArray[_index] subject] objectForKey:@"body"][section] objectForKey:@"title"];
        sectionHeaderLabel.font = [UIFont systemFontOfSize:13];
        [sectionHeaderView addSubview:blackView];
        [sectionHeaderView addSubview:sectionHeaderLabel];
        return sectionHeaderView;
    }
    
}// 自定义段头视图

#pragma mark - DSZClassifyShopsCellDelegate
- (void)didSelectItemWithIndex:(NSInteger)index{

     NSLog(@"%i",index);
    [self performSegueWithIdentifier:@"shops" sender:nil];

}

// 分类表头按钮动作
- (void)tableHeaderBtnClickWithBtn:(UIButton *)btn{
    
    NSLog(@"%i",btn.tag);
    
    [self performSegueWithIdentifier:@"shops" sender:nil];

}

// 分类表头分页按钮动作
- (void)tableHeaderPageBtnClickWithBtn:(UIButton *)btn{
    
    [self removeTimer];
    
    if (self.currentPage != btn.tag - 201) {
        
        self.currentPage = btn.tag - 201;
        
        UIButton *btn = (UIButton *)[self.classifyHeaderView viewWithTag:self.currentPage + 201];
        [self tableHeaderChangePageBtnWithBtn:btn];
    }
    
    [self addTimer];
    
}

// 分类表头分页按钮视图改变
- (void)tableHeaderChangePageBtnWithBtn:(UIButton *)btn{

    btn.alpha = 1;
    
    _lastClikPageBtn.alpha = 0.5;
    
    _lastClikPageBtn = btn;
    
    // 2.计算scrollView滚动的位置
    CGFloat offsetX = (btn.tag - 201) * self.tableHeaderScrollView.frame.size.width;
    CGPoint offset = CGPointMake(offsetX, 0);
    [self.tableHeaderScrollView setContentOffset:offset animated:YES];
}

@end
